@file:OptIn(ExperimentalMaterial3Api::class)

package com.ljj.bitetime.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ljj.bitetime.data.local.database.AppDatabase
import com.ljj.bitetime.item.Order
import com.ljj.bitetime.item.OrderItem
import com.ljj.bitetime.ui.theme.BiteTimeTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Locale

class OrderActivity : ComponentActivity() {
    private val context = this

    companion object {
        const val TAG = "BiteTime.OrderActivity"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            BiteTimeTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    OrderScreen()
                }
            }
        }
    }

    // 从数据库加载订单数据
    suspend fun loadOrdersFromDatabase(context: Context): List<Order> {
        return withContext(Dispatchers.IO) {
            try {
                val database = AppDatabase.getDatabase(context)
                val orderEntities = database.orderDao().getAllOrdersSync()
                val gson = Gson()
                orderEntities.map { entity ->
                    val itemType = object : TypeToken<List<OrderItem>>() {}.type
                    val items: List<OrderItem> = gson.fromJson(entity.itemsJson, itemType)
                    Order(
                        id = entity.id,
                        items = items,
                        totalPrice = entity.totalPrice,
                        timestamp = entity.orderTime
                    )
                }
            } catch (e: Exception) {
                Log.e(TAG, "读取订单时出错: ${e.message}", e)
                emptyList()
            }
        }
    }

    @Composable
    fun OrderScreen() {
        var orders by remember { mutableStateOf<List<Order>>(emptyList()) }
        var loading by remember { mutableStateOf(true) }
        var showScrollToTop by remember { mutableStateOf(false) }
        val listState = rememberLazyListState()
        val scope = rememberCoroutineScope()
        LaunchedEffect(Unit) {
            orders = loadOrdersFromDatabase(context)
            loading = false
        }
        LaunchedEffect(listState) {
            snapshotFlow { listState.firstVisibleItemIndex }
                .collect { index ->
                    showScrollToTop = index > 0
                }
        }
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("我的订单") },
                    modifier = Modifier.background(MaterialTheme.colorScheme.surface),
                    navigationIcon = {
                        IconButton(onClick = { context.finish() }) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = "返回"
                            )
                        }
                    }
                )
            },
            floatingActionButton = {
                if (showScrollToTop && orders.isNotEmpty()) {
                    FloatingActionButton(
                        onClick = {
                            scope.launch {
                                listState.animateScrollToItem(0)
                            }
                        },
                        containerColor = MaterialTheme.colorScheme.primary
                    ) {
                        Icon(
                            imageVector = Icons.Filled.KeyboardArrowUp,
                            contentDescription = "返回顶部"
                        )
                    }
                }
            }
        ) { innerPadding ->
            if (loading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background)
                        .padding(innerPadding),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "加载中...",
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
            } else if (orders.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background)
                        .padding(innerPadding),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无订单记录",
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
            } else {
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background)
                        .padding(innerPadding)
                ) {
                    items(orders.reversed()) { order ->
                        Box(modifier = Modifier.padding(8.dp)) {
                            SwipeableOrderCard(
                                order = order,
                                onOrderChange = {
                                    scope.launch {
                                        orders = loadOrdersFromDatabase(context)
                                    }
                                }
                            )
                        }
                    }
                    item {
                        Spacer(modifier = Modifier.height(72.dp))
                    }
                }
            }
        }
    }

    @Composable
    fun SwipeableOrderCard(
        order: Order,
        onOrderChange: (() -> Unit)
    ) {
        val scope = rememberCoroutineScope()
        var showDeleteDialog by remember { mutableStateOf(false) }
        val dismissState = rememberSwipeToDismissBoxState(
            confirmValueChange = { newValue ->
                when (newValue) {
                    SwipeToDismissBoxValue.Settled -> true
                    SwipeToDismissBoxValue.EndToStart -> {
                        showDeleteDialog = true
                        false
                    }
                    SwipeToDismissBoxValue.StartToEnd -> false
                }
            }
        )
        if (showDeleteDialog) {
            AlertDialog(
                onDismissRequest = { showDeleteDialog = false },
                title = { Text("确认删除") },
                text = { Text("确定要删除此订单吗？") },
                confirmButton = {
                    IconButton(
                        onClick = {
                            scope.launch {
                                try {
                                    val database = AppDatabase.getDatabase(context)
                                    database.orderDao().deleteOrder(order.id)
                                    onOrderChange.invoke()
                                } catch (e: Exception) {
                                    Log.e(TAG, "删除订单失败: ${order.id}", e)
                                }
                            }
                            showDeleteDialog = false
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Done,
                            contentDescription = "删除",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }
                },
                dismissButton = {
                    IconButton(
                        onClick = { showDeleteDialog = false }
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Close,
                            contentDescription = "取消",
                            tint = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            )
        }
        SwipeToDismissBox(
            state = dismissState,
            backgroundContent = {},
            content = {
                OrderCard(order = order)
            },
            enableDismissFromStartToEnd = false,
            enableDismissFromEndToStart = true
        )
    }

    @SuppressLint("DefaultLocale")
    @Composable
    fun OrderCard(order: Order) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(
                modifier = Modifier
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(16.dp)
            ) {
                // 订单头部信息
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "订单号: ${order.id.substring(0..7)}",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(order.timestamp),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                Spacer(modifier = Modifier.height(12.dp))
                // 订单项目列表
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    order.items.forEach { orderItem ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = orderItem.dish.name,
                                style = MaterialTheme.typography.bodyMedium
                            )
                            Text(
                                text = "x${orderItem.quantity}",
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.height(12.dp))
                // 订单总价
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "总价",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = "￥${String.format("%.2f", order.totalPrice)}",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
        }
    }
}